package com.ophiux.common.utils;

import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class XmlUtil {
	private static XmlUtil xmlUtil;

	public static XmlUtil getInstance() {
		if (xmlUtil == null) {
			xmlUtil = new XmlUtil();
		}
		return xmlUtil;
	}

	public String getValue(String xml, String key) {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = null;
		try {
			db = dbf.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}

		InputSource eris = new InputSource(new StringReader(xml));
		Document erDocument = null;
		try {
			erDocument = db.parse(eris);
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Element root = erDocument.getDocumentElement();
		NodeList nodeEncrypt = root.getElementsByTagName(key);
		String value = nodeEncrypt.item(0).getTextContent();

		return value;
	}

	public String mapToXml(HashMap<String, String> map) {
		if (map == null) {
			return "";
		}
		StringBuffer xmlStr = new StringBuffer("<xml>");
		for (String key : map.keySet()) {
			String value = (String) map.get(key);
			xmlStr = buildXml(xmlStr, key, value);
		}
		xmlStr.append("</xml>");
		return xmlStr.toString();
	}

	public StringBuffer buildXml(StringBuffer xmlStr, String nodeName,
			String value) {
		xmlStr.append("<" + nodeName + ">").append(value)
				.append("</" + nodeName + ">");
		return xmlStr;
	}
}